<template>
    <div class="header block">
        <div class="detail">
            <div class="search">
                发薪时间
                <el-date-picker v-model="payDateSolt" type="daterange" class="date-solt screen-i" unlink-panels
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleCurrentChange"
                    value-format="YYYY-MM-DD" :shortcuts="shortcuts" />
                领薪时间
                <el-date-picker v-model="paidTime" type="daterange" class="date-solt screen-i" unlink-panels
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleCurrentChange"
                    value-format="YYYY-MM-DD" :shortcuts="shortcuts" />
                <el-select v-model="searchType" filterable placeholder="搜索方式" class="screen-i search-type">
                    <el-option label="搜名称" :value="0" />
                    <el-option label="搜备注" :value="1" />
                </el-select>
                <input type="text" :placeholder="searchType ? '请输入备注信息' : '请输入人员名称'" class="input search-input screen-i"
                    v-model="searchText" style="width:150px" @keydown.enter="search" />
                <el-select v-model="payType" filterable placeholder="筛选领薪状态" class="screen-i drop-down"
                    @change="handleCurrentChange">
                    <el-option :label="item.dictLabel" :value="item.dictValue" v-for="(item, index) in payTypeList"
                        v-bind:key="index">{{ item.dictLabel }}</el-option>
                </el-select>
                <el-select v-model="enterpriseName" filterable placeholder="请选择派遣单位" class="screen-i">
                    <el-option :label="item.serveCompanyName" :value="item.id" v-for="(item, index) in enterpriseList"
                        v-bind:key="index">{{ item.serveCompanyName }}</el-option>
                </el-select>
                <div>
                    <button class="btn screen-i" @click="search">搜索</button>
                    <button class="btn-white screen-i" @click="onReset">
                        重置
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="container block">
        <view class="tool">
            <!-- <el-icon><remove /></el-icon>selects -->
            <el-button @click="stopPay" style="margin-right:13px;background:#FF7E68;color:#fff;"
                :disabled="selects.length === 0">
                <i class="el-icon el-icon-remove" />
                停止发薪
            </el-button>
            <export-button type="success" @export="onExport"></export-button>
<!--            <button class="btn-green" @click="onExport">-->
<!--                <i class="el-icon el-icon-upload2" />-->
<!--                导出-->
<!--            </button>-->
            <el-button class="btn-white download-btn" @click="applyReceipt"
                style="width: 160px;margin-left: 10px;border:1px solid #1989FA;color:#1989FA;">
                <i class="el-icon el-icon-download" />
                一键申请回单
            </el-button>
            <el-button class="btn-white download-btn" @click="downloadPayrollRecordEle"
                style="width: 180px;margin-left: 10px;border:1px solid #00D679;color:#00D679;"
                :disabled="selects.length === 0">
                <i class="el-icon el-icon-download" />
                一键下载微信回单
            </el-button>
        </view>
        <div class="table">
            <el-table :data="tableData" style="width: 100%" :header-row-style="{ color: '#202536' }"
                :row-style="{ color: '#5E617D' }" @selection-change="handleSelectionChange">
                <el-table-column type="selection" />

                <el-table-column prop="userName" label="用户名" width="120">
                    <template #default="scope">
                        <!-- :class="[scope.row.nickName?.length ?? 0 + scope.row.userName.length <= 10 ? 'align-items' : '']" -->
                        <div>
                            <div>
                                {{ scope.row.userName }}
                            </div>
                            <div v-if="scope.row.nickName">
                                <el-tooltip class="box-item" effect="dark" content="此处为备注名" placement="top-start">
                                    <div class="nickName">
                                        {{ scope.row.nickName ? '(' + scope.row.nickName + ')' : '' }}
                                    </div>
                                </el-tooltip>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="serveCompanyName" label="派遣单位名称" />
                <el-table-column prop="projectName" label="项目名称" />
                <el-table-column prop="paymentAmount" label="支付金额" :formatter="(row: { paymentAmount: string }) => ('￥' + row.paymentAmount)
                    " />
                <!-- .领薪记录新增审核状态，领薪状态。新增派遣单位名称筛选 -->
                <!-- 0=审核中,1=审核通过(可领),2=审核失败(或取消申请) -->
                <el-table-column prop="payTime" label="发薪时间" />
                <el-table-column prop="auditStatus" label="审核状态" :formatter="(row: { auditStatus: number }) => (row.auditStatus === 1 ? '审核通过' : row.auditStatus === 2 ? '审核失败' : '审核中')
                    " />
                <el-table-column prop="statusMsg" label="领薪状态" />
                <el-table-column prop="getSalaryTime" label="领薪时间" />
                <el-table-column prop="billStatus" label="回单状态" :formatter="(row: { billStatus: number | null }) => (row.billStatus === null ? '未申请' : row.billStatus === 1 ? '申请中' : row.billStatus === 2 ? '已完成' : '未申请')
                    " />
                <el-table-column prop="detailRemarks" label="备注" />
                <el-table-column prop="flowCode" label="流程单号" width="200px" />
            </el-table>
            <!-- , 80,100 -->
            <el-pagination class="pagination" v-model:currentPage="pageNum" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </el-pagination>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { openContractDetail } from '@/api/contract'
import axios from 'axios'
import {
    payrollRecord,
    stopPay,
    PayrollRecordDto,
    payScreenType
} from '@/api/pay'
import { payrollRecordExport } from '@/api/export'
import { shortcuts } from '@/utils/global'
import { payrollRecordEle, downloadPayrollRecordEle } from '@/api/operation'
import { EnterpriseDto, getEnterpriseNameList } from '@/api/enterprise'
import { dateFormat, closewin, downLoadFile } from '@/utils/util'
import store from '@/store/index'
import router from '@/router'
export default defineComponent({
    name: 'PayrollRecord',
    data() {
        return {
            active: '全部',
            total: 0,
            pageSize: 10,
            pageNum: 1,
            tableData: [] as PayrollRecordDto[],
            payDateSolt: [] as string[],
            paidTime: '', // 领薪时间
            searchValue: '',
            searchText: '',
            selects: [] as string[],
            shortcuts: shortcuts,
            enterpriseName: '',
            enterpriseList: [] as EnterpriseDto[], // 派遣单位列表
            payTypeList: [] as { dictLabel: string; dictValue: string }[],
            payType: '' as number | string,
            searchType: 0
        }
    },
    created() {
        // 被跳转到该页面恢复原页面数据
        this.payDateSolt = [(dateFormat('YY-mm', new Date()) + '-01'), dateFormat('YY-mm-dd', new Date())]
        console.log(this.payDateSolt, 'payDateSolt')
        if (/tip/.test(router.options.history.base)) {
            ElMessageBox.alert('回单正在下载中，您可以在该界面继续操作')
            const channel = new BroadcastChannel('new_tab_payroll')
            let isLoad = 0
            channel.onmessage = e => {
                const data = JSON.parse(e.data)
                this.enterpriseName = data.enterpriseName
                this.pageNum = data.pageNum
                this.pageSize = data.pageSize
                this.paidTime = data.paidTime
                this.payDateSolt = data.payDateSolt
                this.payType = data.payType
                this.searchValue = data.searchValue
                this.searchText = data.searchText
                isLoad = 1
                channel.postMessage('payroll_close')
                channel.close()
                this.init()
            }
            setTimeout(() => {
                if (!isLoad) {
                    window.location.search = ''
                }
                channel.close()
            }, 5000)
        } else {
            this.init()
        }
    },
    methods: {
        init() {
            this.handleCurrentChange()
            this.getEnterpriseNameList()
            this.getPayScreenType()
        },
        windowOpen() {
            window.open(
                window.location.pathname +
                '?tip#/payrollrecord'
            )
            const channel = new BroadcastChannel('new_tab_payroll')
            const timer = setInterval(() => {
                channel.postMessage(JSON.stringify({
                    payDateSolt: this.payDateSolt,
                    paidTime: this.paidTime,
                    searchValue: this.searchValue,
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,
                    enterpriseName: this.enterpriseName,
                    payType: this.payType,
                    searchText: this.searchText
                }))
                console.log('postMessage')
            }, 50)
            channel.onmessage = e => {
                if (e.data === 'payroll_close') {
                    clearInterval(timer)
                    channel.close()
                }
            }
        },
        // 查询公司下派遣单位列表
        async getEnterpriseNameList() {
            const result = await getEnterpriseNameList()
            this.enterpriseList = result.list
        },
        handleCurrentChange() {
            console.log(this.payDateSolt, 'payDateSolt')
            payrollRecord({
                searchText: this.searchType ? '' : this.searchValue,
                beginPayTime: this.payDateSolt ? this.payDateSolt[0] : '',
                endPayTime: this.payDateSolt ? this.payDateSolt[1] : '',
                beginGetSalaryTime: this.paidTime ? this.paidTime[0] : '',
                endGetSalaryTime: this.paidTime ? this.paidTime[1] : '',
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                serveCompanyId: this.enterpriseName,
                status: this.payType === 'ALL' ? '' : this.payType,
                detailRemarks: this.searchType ? this.searchValue : ''
            }).then(res => {
                this.tableData = res.list.map(item => {
                    item.userName =
                        item.userName +
                        '(' +
                        (item.idCardNo + '').slice(14) +
                        ')'
                    return item
                })
                this.total = res.total
                console.log(res.list, 'resres')
            })
        },
        // 批量停止发薪
        async stopPay() {
            await stopPay(this.selects.join(','))
            ElMessage.error('停止发薪成功')
            await this.handleCurrentChange()
        },
        // 一键申请回单
        applyReceipt() {
            payrollRecordEle({
                ids: this.selects.join(','),
                beginPayTime: this.payDateSolt ? this.payDateSolt[0] : '',
                endPayTime: this.payDateSolt ? this.payDateSolt[1] : '',
                beginGetSalaryTime: this.paidTime ? this.paidTime[0] : '',
                endGetSalaryTime: this.paidTime ? this.paidTime[1] : ''
            }).then(() => {
                ElMessage.success('申请成功')
                this.handleCurrentChange()
            })
        },
        // 下载申请回单 downloadPayrollRecordEle
        async downloadPayrollRecordEle() {
            // this.downloadReceipt()
            this.downloadReceiptOld()
        },
        async downloadReceiptOld() {
            const result = await downloadPayrollRecordEle({
                ids: this.selects.join(',')
            })
            this.windowOpen()

            document.title = '正在下载中...'
            const loading = await ElLoading.service({
                fullscreen: true,
                text: '回单正在下载中，您可以在新界面继续操作'
            })
            const files = await axios({
                url:
                    'https://1403244436326619.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/zip-service/zip-oss/',
                method: 'post',
                data: result
            })
            window.location.href = files.data
            await this.$message.success('导出成功！')
            await loading.close()
            closewin()
        },

        async downloadReceipt() {
            const result = await downloadPayrollRecordEle({
                ids: this.selects.join(',')
            })
            this.windowOpen()
            document.title = '正在下载中...'
            const loading = await ElLoading.service({
                fullscreen: true,
                text: '回单正在下载中，您可以在新界面继续操作'
            })
            console.log(result, 'result')
            const files = await axios({
                url:
                    'https://1403244436326619.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/zip-oss/zip-oss/',
                method: 'post',
                responseType: 'blob',
                data: result
            })
            // window.location.href =
            // process.env.VUE_APP_BASE_URL +
            // '/common/downloadBatchBill?delete=true&uuid=' +
            // str
            console.log(files, 'files')
            const blob = new Blob([files.data])
            const downloadElement = document.createElement('a')
            const href = window.URL.createObjectURL(blob)
            downloadElement.href = href
            downloadElement.download =
                '回单' + dateFormat('YY-mm-dd HH:MM', new Date()) + '.zip'
            document.body.appendChild(downloadElement)
            downloadElement.click()
            document.body.removeChild(downloadElement)
            window.URL.revokeObjectURL(href)

            await loading.close()
            await this.$message.success('导出成功！')
            closewin()
        },
        handleSizeChange() {
            this.pageNum = 1
            this.handleCurrentChange()
        },
        search() {
            this.searchValue = this.searchText
            this.pageNum = 1
            this.handleCurrentChange()
        },
        onReset() {
            this.searchText = ''
            this.payDateSolt = []
            this.enterpriseName = ''
            this.search()
        },
        async onExport() {
            const result = await payrollRecordExport({
                ids: this.selects.join(','),
                searchText: this.searchValue,
                serveCompanyId: this.enterpriseName,
                beginPayTime: this.payDateSolt ? this.payDateSolt[0] : '',
                endPayTime: this.payDateSolt ? this.payDateSolt[1] : '',
                beginGetSalaryTime: this.paidTime ? this.paidTime[0] : '',
                endGetSalaryTime: this.paidTime ? this.paidTime[1] : '',
                status: this.payType === 'ALL' ? '' : this.payType
            }, {
                loading: true
            })
            console.log(result, 'result')
            if (!result.fileUrl && result.exportStatus === 0) {
                store.commit('getLongPollingFile', result)
            } else {
                axios({
                    url: result.fileUrl,
                    method: 'GET',
                    responseType: 'blob'
                }).then(async (response) => {
                    await downLoadFile(response, result.exportType, result.updateTime, result.remark)
                    await this.$message.success('导出成功！')
                })
            }
            // window.location.href =
            //     process.env.VUE_APP_BASE_URL +
            //     '/common/download?delete=true&fileName=' +
            //     result
            // this.$message.success('导出成功！')
        },
        handleSelectionChange(selects: { id: string }[]) {
            this.selects = selects.map(item => item.id)
            console.log(this.selects)
        },
        async goDetail(flowId: string) {
            const result = await openContractDetail(flowId)
            window.open(result.consoleUrl)
        },
        getPayScreenType() {
            payScreenType('saas-pay-get-status').then(res => {
                this.payTypeList = res
            })
        }
    }
})
</script>

<style lang="stylus" scoped>
table()
.header.block
    justify-content space-between
    display flex
    padding 10px 24px
.block
    padding: 10px 24px 0;
:deep().date-solt
    width 241px
    margin-right 20px
.operation
    .btn,.btn-green
        width 113px
        height 40px
        margin-left 20px
.tool
    float: right

:deep().el-tabs__header.is-top
    display inline-block
:deep().el-tabs__nav-scroll
    padding-right 20px

:deep().el-input__inner
    height 42px
.screen-i
    margin 10px 10px
.drop-down
    width 150px
.search-type
    width 100px
    margin-right 8px
.nickName
    color #FFC53D
</style>
